import re
from django.utils import simplejson 
import os
from google.appengine.ext.webapp import template

import logging
from logging import error, info, debug
from google.appengine.api.labs import taskqueue

from models import Feed, FeedContent, UserFeeds, UserRatings
from google.appengine.api import urlfetch
from google.appengine.api.urlfetch import InvalidURLError, DownloadError
from google.appengine.runtime import  DeadlineExceededError 
from google.appengine.runtime.apiproxy_errors import InterruptedError
import feedparser

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from google.appengine.api import users
from google.appengine.ext import db
import datetime


class Rate(webapp.RequestHandler):
	def post( self ):
		id = self.request.get( "id" )
		value = self.request.get( "value" )

		feedContent = FeedContent.get_by_id(int(id))
		if feedContent is None:
			return

		user = users.get_current_user()

		pur = UserRatings.all().filter("feedContent = ",feedContent).filter("user =", user).fetch(10)
		if len( pur ) == 0:
			ur = UserRatings(
				feedContent = feedContent,
				user = user,
				rate = float(value)
			)
		else:
			ur = pur[0]
			ur.rate = float( value )

		ur.put()


class Show(webapp.RequestHandler):
	def get(self):

		user = users.get_current_user()

		if not user:
			self.redirect(users.create_login_url(self.request.uri))
			return

		q=""
		uf = UserFeeds.all().filter("user = ", user).fetch(1000)
		for k in uf:
				k.feed.id = k.feed.key().id() 
				q= q + str(k.feed.title.encode("utf8")) + "<br>"
			
		info( uf )	
		template_values = {
		'feeds'        : uf,
		'url'          : "",
		'url_linktext' : "",
		'username'     : user.nickname(),
		'logout'       : users.create_logout_url("/")
		}

		path = os.path.join(os.path.dirname(__file__), 'show.html')
		result = template.render(path, template_values)
		self.response.out.write(result)


class ShowFeed(webapp.RequestHandler):
	def post( self ):
		id = self.request.get( "id" )
		feed = Feed.get_by_id( int( id ) )
		rows = FeedContent.all().filter( "feed =", feed ).fetch( 20 )

		user = users.get_current_user()


		list = []
		for row in rows:
			if type( row.date ).__name__ != 'datetime':
				continue

			ur = UserRatings.all().filter( "feedContent =", row).filter( "user =", user).fetch( 1 )
			rate = False
			if len( ur ) > 0:
				rate = ur[0].rate
			
			diffDate = datetime.datetime.now() - row.date  
			p = re.compile( "(\d*) days" )
			days = p.search( str( diffDate ) )
			if days is None :
				daysStr = ""
			else:
				daysStr = days.group(1) + " days ago" 

			list.append( simplejson.dumps({
				"id": row.key().id(),
				"title": row.title,
				"content": row.content,
				"date": str(row.date),
				"days": daysStr,
				"rate": rate
			}))

		self.response.out.write("[" + ",".join(list) + "]")


def main():
  logging.getLogger().setLevel(logging.DEBUG)
  wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
    ('/rate', Rate),
    ('/show', Show),
    ( '/showfeed',  ShowFeed)
  ]))


if __name__ == '__main__':
  main()



